import { useState, useCallback, useEffect } from 'react';
import { message } from 'antd';
import { platformPermissionApi } from '../../services/platform/api/platformPermissionApi';
import { useAsyncState } from '../common/useErrorHandler';

export interface PlatformRole {
  id: string;
  name: string;
  code: string;
  description?: string;
  permissions: string[];
  status: number | 'active' | 'inactive';
  createTime?: string;
  updateTime?: string;
  menuCodes?: string[];
}

export interface MenuData {
  key: string;
  title: string;
  description: string;
  icon?: string;
  order?: number;
  hidden?: boolean;
  requiredPermissions?: string[];
}

export interface RolesPageQuery {
  current: number;
  size: number;
  search?: string;
}

// 平台权限管理hooks
export const usePlatformPermissions = () => {
  // 状态管理
  const [roles, setRoles] = useState<PlatformRole[]>([]);
  const [menus, setMenus] = useState<MenuData[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchText, setSearchText] = useState('');

  const { executeAsync, hasAnyLoading, hasError, error, clearError } = useAsyncState();

  // 获取菜单数据
  const loadMenus = useCallback(async () => {
    return executeAsync('loadMenus', async () => {
      const response = await platformPermissionApi.getAllMenus();
      const menuData = response.map((menu: any) => ({
        key: menu.key,
        title: menu.label,
        description: menu.path || '',
        icon: menu.icon,
        order: menu.order,
        hidden: menu.hidden,
        requiredPermissions: menu.requiredPermissions
      }));
      setMenus(menuData);
      return menuData;
    });
  }, [executeAsync]);

  // 获取角色数据
  const loadRoles = useCallback(async () => {
    return executeAsync('loadRoles', async () => {
      const response = await platformPermissionApi.getRolesWithMenusPage({
        current: pagination.current,
        size: pagination.pageSize,
        search: searchText,
      });
      
      const rolesData = response.records || [];
      setRoles(rolesData);
      setPagination(prev => ({
        ...prev,
        total: response.totalElements || 0,
        current: response.number + 1 || prev.current,
      }));
      
      return rolesData;
    });
  }, [executeAsync, pagination.current, pagination.pageSize, searchText]);

  // 获取角色菜单权限
  const getRoleMenus = useCallback(async (roleCode: string): Promise<string[] | null> => {
    return executeAsync('getRoleMenus', async () => {
      const response = await platformPermissionApi.getRoleMenuCodes(roleCode);
      return response || [];
    });
  }, [executeAsync]);

  // 更新角色权限
  const updateRolePermissions = useCallback(async (roleCode: string, menuCodes: string[]) => {
    return executeAsync('updateRolePermissions', async () => {
      await platformPermissionApi.assignMenusToRole(roleCode, menuCodes);
      message.success('权限更新成功');
      // 重新加载数据
      await loadRoles();
    });
  }, [executeAsync, loadRoles]);

  // 搜索处理
  const handleSearch = useCallback((value: string) => {
    setSearchText(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  // 分页处理
  const handlePageChange = useCallback((page: number, pageSize?: number) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize: pageSize || prev.pageSize,
    }));
  }, []);

  // 刷新数据
  const refresh = useCallback(async () => {
    await Promise.all([loadMenus(), loadRoles()]);
  }, [loadMenus, loadRoles]);

  // 初始化数据
  useEffect(() => {
    refresh();
  }, [refresh]);

  // 当分页或搜索条件变化时重新加载
  useEffect(() => {
    loadRoles();
  }, [pagination.current, pagination.pageSize, searchText]);

  return {
    // 数据状态
    roles,
    menus,
    pagination,
    searchText,
    
    // 加载状态
    loading: hasAnyLoading,
    hasError,
    error,
    clearError,
    
    // 操作方法
    loadMenus,
    loadRoles,
    updateRolePermissions,
    getRoleMenus,
    handleSearch,
    handlePageChange,
    refresh,
  };
};

// 菜单分组hooks
export const useMenuGroups = () => {
  const getMenusByGroup = useCallback((menus: MenuData[]) => {
    const groups: Record<string, MenuData[]> = {};
    menus.forEach(menu => {
      let category = 'other';
      if (menu.description.includes('/dashboard')) category = 'dashboard';
      else if (menu.description.includes('/tenant')) category = 'tenant';
      else if (menu.description.includes('/user') || menu.description.includes('/role') || menu.description.includes('/permission')) category = 'user';
      else if (menu.description.includes('/system') || menu.description.includes('/setting')) category = 'system';
      else if (menu.description.includes('/ticket')) category = 'monitor';
      
      if (!groups[category]) {
        groups[category] = [];
      }
      groups[category].push(menu);
    });
    return groups;
  }, []);

  const getCategoryName = useCallback((category: string) => {
    const categoryMap: Record<string, string> = {
      'dashboard': '仪表盘',
      'tenant': '租户管理',
      'user': '用户管理',
      'system': '系统管理',
      'monitor': '监控管理',
      'other': '其他'
    };
    return categoryMap[category] || '其他';
  }, []);

  return {
    getMenusByGroup,
    getCategoryName,
  };
};